package 哈希表.快乐数;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/13 16:51
 * @description:编写一个算法来判断一个数 n 是不是快乐数
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int num = 17;
        System.out.println(isHappy2(num));
    }


    //暴力法无法解决，超出时间限制！！！！！
    public static boolean isHappy(int n) {
        int result = -1;
        try {
            while (result != 1){
                int happyNum = numToHappyNum(n);
                n = happyNum;
                result = happyNum;
            }
        }catch (Exception e){
            return false;
        }

        return true;
    }


    public static int numToHappyNum(int num){
        List<Integer> list = new ArrayList<>();
        int sum = 0;
        while (num/10 != 0){
            list.add(num % 10);
            num = num / 10;
        }
        list.add(num);
        for (int i = 0; i < list.size(); i++) {
            sum += list.get(i)*list.get(i);
        }
        return sum;
    }


    /**
     * 哈希表解决法 通过引入hashSet,将一些非快乐数的结果存入set集合中，可以节约我们的运算时间
     */
    private static int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }

    public static boolean isHappy2(int n) {
        Set<Integer> seen = new HashSet<>();
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);
            n = getNext(n);
        }
        return n == 1;
    }

    /**
     * 快慢指针 这里相当于验证是否存在环形链表  妙啊
     */
    public static boolean isHappy3(int n) {
        int slowRunner = n;
        int fastRunner = getNext(n);
        //如果 n 是一个快乐数，即没有循环，那么快跑者最终会比慢跑者先到达数字 1。
        //如果 n 不是一个快乐的数字，那么最终快跑者和慢跑者将在同一个数字上相遇
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);
            fastRunner = getNext(getNext(fastRunner));
        }
        return fastRunner == 1;
    }




}
